package com.yzf.enterprise.framework.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author : zuoyu
 * @description : 事务数据源
 * @date : 2020-06-01 17:30
 **/
@Component
public class AtomikosDataSourceCreator {
    /**
     * 创建数据源
     *
     * @param dataSourceProperty 数据源信息
     * @return 数据源
     */
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setUrl(dataSourceProperty.getUrl());
        mysqlXADataSource.setPassword(dataSourceProperty.getPassword());
        mysqlXADataSource.setUser(dataSourceProperty.getUsername());
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXADataSource);
        xaDataSource.setMinPoolSize(5);
        xaDataSource.setBorrowConnectionTimeout(60);
        xaDataSource.setMaxPoolSize(20);
        xaDataSource.setXaDataSourceClassName(dataSourceProperty.getDriverClassName());
        xaDataSource.setTestQuery("SELECT 1 FROM DUAL");
        xaDataSource.setUniqueResourceName(dataSourceProperty.getPollName());
        return xaDataSource;
    }
}
